/*
 * @(#)GSBusOrderProcesser.java 
 *
 * Project: BUS
 *
 * Modify Information:
 * =============================================================================
 *   Author       Date       Description
 *   simon                   建立
 *   Jenny Li     2006-4-5   修改方法getSql，添加了查询字段P15
 *                           添加方法submitOrderDetailToApep，orderSubmitToApep
 *   Jenny Li     2006-4-12  修改方法submitOrderDetailToApep                         
 *   
 * Copyright Notice:
 * =============================================================================
 *    Copyright (c) 2001-2005 Beijing HiTRUST Technology Co., Ltd. 1808 Room, 
 *        Science & Technology Building, No. 9 South Street, Zhong Guan Cun, 
 *        Haidian District, Beijing ,100081, China All rights reserved.
 *
 *    This software is the confidential and proprietary information of
 *        Beijing HiTRUST Technology Co., Ltd. ("Confidential Information").
 *        You shall not disclose such Confidential Information and shall use it
 *        only in accordance with the terms of the license agreement you entered
 *        into with HiTRUST.
 *
 * Warning:
 * =============================================================================
 * 
 */
package com.hitrust.gs.business;

import com.apep.connect.APEPRequest;
import com.apep.connect.APEPResponse;
import com.apep.connect.client.APEPClient;
import com.apep.connect.server.APEPService;
import com.apep.lib.xml.SampleElement;
import com.apep.lib.xml.SampleXMLDocument;
import com.hitrust.gs.integration.socket.GSApepClient;
import com.hitrust.gs.integration.socket.GSClientSocket;
import com.hitrust.gs.lib.GSBaseConstants;
import com.hitrust.gs.lib.GSLogWriter;
import com.hitrust.gs.lib.GSSystemConfigurator;
import com.hitrust.gs.lib.db.GSBaseDAO;
import com.hitrust.gs.service.GSBaseManager;
import com.hitrust.gs.service.GSBaseProcesser;
import com.hitrust.gs.util.DefineDic;
import com.hitrust.gs.util.ParameterFactory;
import com.hitrust.gs.util.date.DateUtil;
import com.hitrust.gs.util.exception.*;
import com.hitrust.gs.vo.GSBusOrderManufactureVO_;
import com.hitrust.gs.vo.GSOrderAuditVO;
import com.hitrust.gs.vo.GSOrderAuthorizeQueryVO;
import com.hitrust.gs.vo.GSOrderAuthorizeSaveVO;
import com.hitrust.gs.vo.GSOrderAuthorizeVO;
import com.hitrust.gs.vo.GSOrderManufactureVO;
import com.hitrust.gs.vo.GSOrderReceiveQueryVO;
import com.hitrust.gs.vo.GSOrderVO;
import com.hitrust.gs.dao.*;
import com.hitrust.gs.bean.*;

import framework.core.ConstDefine;
import framework.core.SystemConfigurator;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;

import system.LoginContext;

/**
 * @author simonyi
 * 
 * TODO To change the template for this generated type comment go to Window -
 * Preferences - Java - Code Style - Code Templates
 */
public class GSBusOrderProcesser implements GSBaseProcesser {
      
    
    public String getSql(GSOrderAuthorizeQueryVO vo) {
        // 构造订单查询语句,条件:输入条件+状态为'已提交'+申请人不是自己
        StringBuffer tSql = new StringBuffer("select distinct B.GS_ORDER_DETAIL_ID as P1,B.GS_CONCENTRICITY_ID as P2,");
        tSql.append("C.APEP_CODE as P3_,C.NAME as P3,C.SPEC as P4,");
        tSql.append("C.MODEL as P5,C.PRODUCT_BRAND as P6,E.name as P7,");
        tSql.append("C.DRAWING_PIECE_CODE as DRAWING_PIECE_CODE,");
        tSql.append("A.GS_WORKCORP_ID as P7_,C.IS_TRADEFLAT_PRODUCT as P8,F.code as P9_,");
        tSql.append("F.name as P9,B.GS_ORDER_COUNT as P10,C.PRODUCT_UNIT as P10_,");
        tSql.append("C.UNIT_PRICE as P11,(B.GS_ORDER_COUNT * C.UNIT_PRICE) as P12,");
        tSql.append("B.GS_DELIVER_GOODS_DATE as P13,B.GS_DELIVER_GOODS_TIME as P14,F.IS_TRADEFLAT_PROVIDER as P15,");
        tSql.append("A.GS_ORDER_CREATE_DATE,A.GS_ORDER_TEMPID,b.gs_balance_mode as P16,C.IS_NORMAL ");
        tSql.append(" from GS_ORDER A,GS_ORDER_DETAIL B,t_product C,t_warehouse e,t_provider F ");
        tSql.append(" where A.GS_ORDER_TEMPID=B.GS_ORDER_TEMPID and B.GS_CONCENTRICITY_ID=C.CONCENTRICITY_CODE");
        tSql.append(" and b.gs_manufacture_id = c.APEP_CODE");
        tSql.append(" and A.GS_WORKCORP_ID=e.code");
        tSql.append(" and C.PROVIDER_CODE = F.code");

        tSql.append(" and B.GS_ORDER_DETAIL_STATUS ='6' ");

        tSql.append(" and b.GS_ORDERRETURN_SIGN in ('"+GSBaseConstants.APEP_RETURN_SIGN_SUCCESS+"','-1') ");
        // 订单明细id
        if (vo.orderDetailId != null) {
            tSql.append(" and B.GS_ORDER_DETAIL_ID like '%" + vo.orderDetailId.trim() + "%'");
        }
        // 订货单位
        if (vo.deptId != null) {
            tSql.append(" and A.GS_WORKCORP_ID like '" + vo.deptId + "%'");
        }
        // 集中编码
        if (vo.concentricityId != null) {
            tSql.append(" and B.GS_CONCENTRICITY_ID like '%" + vo.concentricityId.trim() + "%'");
        }
        // 关键字
        if (vo.manufInfo != null) {
            tSql.append(" and (C.NAME like '%" + vo.manufInfo.trim() + "%'");
            tSql.append(" or C.MODEL like '%" + vo.manufInfo.trim() + "%'");
            tSql.append(" or C.UNIT_PRICE like '%" + vo.manufInfo.trim() + "%'");
            tSql.append(" or C.PRODUCT_BRAND like '%" + vo.manufInfo.trim() + "%'");
            tSql.append(" or C.APPENDER_PROPERTY like '%" + vo.manufInfo.trim() + "%'");
            tSql.append(" or C.MANUFATURER like '%" + vo.manufInfo.trim() + "%')");
        }
        // 供应商
        if (vo.providerName != null) {
            tSql.append(" and F.full_name like '%" + vo.providerName.trim() + "%'");
        }
        // 开始时间
        if (!"".equals(vo.beginDate)) {
            tSql.append(" and to_char(to_date(A.GS_ORDER_CREATE_DATE,'YYYY-MM-DD HH24:mi:ss'),'YYYY-MM-DD') >='" + vo.beginDate.replace('/', '-') + "'");

        }
        // 结束时间
        if (!"".equals(vo.endDate)) {

            tSql.append(" and to_char(to_date(A.GS_ORDER_CREATE_DATE,'YYYY-MM-DD HH24:mi:ss'),'YYYY-MM-DD') <='" + vo.endDate.replace('/', '-') + "'");
        }
        // 图件号
        if(vo.drawingpiececode != null && !vo.drawingpiececode.equals("")){
            tSql.append(" and C.DRAWING_PIECE_CODE like '%" + vo.drawingpiececode.trim() + "%'");
        }
        // 判断VO对象中产品种类是否存在
        if(vo.manuftype1 != null){
            if(vo.manuftype1.equals("0")){
                tSql.append(" and c.CATEGORY_CODE like '%'");
            }else if(vo.manuftype2.equals("0")){
                tSql.append(" and exists (select CODE from T_PRODUCT_CATEGORY category where c.CATEGORY_CODE = category.CODE and (category.CODE = '" + vo.manuftype1 + "' or category.CATEGORY_ID1= '" + vo.manuftype1 + "'))");
            }else if(vo.manuftype3.equals("0")){
                tSql.append(" and exists (select CODE from T_PRODUCT_CATEGORY category where c.CATEGORY_CODE = category.CODE and (category.CODE = '" + vo.manuftype2 + "' or category.CATEGORY_ID2= '" + vo.manuftype2 + "'))");
            }else{
                tSql.append(" and c.CATEGORY_CODE like '%" + vo.manuftype3 + "%'");
            }
        }
        tSql.append(" order by A.GS_ORDER_CREATE_DATE desc");
        GSLogWriter.debug(this, tSql.toString());

        return tSql.toString();
    }

    /**
     * 查询可审核的订单明细数量
     * 
     * @param operatorBean
     * @param vo
     * @return
     * @throws GSException
     */
    public int getAllAuthorizeOrderDetailCount(GSOrderAuthorizeQueryVO vo) throws GSException {
        GSBusOrderDAO ordd = new GSBusOrderDAO();
        String tSql = new StringBuffer("select count(*) from (").append(getSql(vo)).append(")").toString();
        try {
            return ordd.queryRowNum(tSql, null);
        } catch (Exception e) {
            throw new GSException(GSException.E19999, GSException.E19999_MSG);
        }

    }

    /**
     * 查询可审核的订单明细
     * 
     * @param operatorBean
     * @param vo
     * @return
     * @throws GSException
     */
    public ArrayList getAllAuthorizeOrderDetail(GSOrderAuthorizeQueryVO vo, int pageNo, int pageSize) throws GSException {
        GSBusOrderDAO ordd = new GSBusOrderDAO();
        String tSql = getSql(vo);
        // 执行订单查询,得到订单信息，包括订单号、产品代号和申请人代号
        ArrayList orderDetailList = null;
        try {
            orderDetailList = ordd.executeQuery(new GSOrderAuthorizeVO(), tSql, null, pageNo, pageSize);

        } catch (Exception e) {
            throw new GSException(GSException.E20055, GSException.E20055_MSG);
        }

        return orderDetailList;
    }

    /**
     * 根据订单号得到所需的订单细节(for订单核准),已作废
     * 
     * @param orderId
     * @return
     * @throws GSException
     */
    public GSOrderVO getOrderAndManufactureForAuthorize(String orderId) throws GSException {
        GSOrderDAO tGSOrderDAO = new GSOrderDAO();
        GSProviderDAO tGSProviderDAO = new GSProviderDAO();
        GSOrderVO tGSOrderVO = new GSOrderVO();
        Connection tConn = null;
        try {
            tConn = tGSOrderDAO.getConnetion();
            // 根据订单编号查询订单对象和订单明细对象
            GSOrderBean orderBean = tGSOrderDAO.getOrderByTempID(orderId);
            tGSOrderVO.orderid = orderBean.getGs_order_tempid();
            tGSOrderVO.category = GSBaseManager.getOrderCategoryName(orderBean.getGs_order_category());
            tGSOrderVO.orderStatus = GSBaseManager.getOrderStatusName(orderBean.getGs_order_status());
            tGSOrderVO.tList = new ArrayList();
            tGSOrderVO.pList = new ArrayList();
            // 根据订单编号查询订单明细对象
            ArrayList tOrderDetailList = tGSOrderDAO.queryOrderAndDetailForAuthorize(tConn, orderId);
            if (tOrderDetailList.size() > 0) {

                for (int i = 0; i < tOrderDetailList.size(); i++) {
                    GSOrderAuthorizeVO tGSOrderAuthorizeVO = (GSOrderAuthorizeVO) tOrderDetailList.get(i);
                    String[] tStr = new String[15];

                    tStr[0] = tGSOrderAuthorizeVO.detailId;
                    tStr[1] = tGSOrderAuthorizeVO.concentricityId;
                    tStr[2] = tGSOrderAuthorizeVO.manufactureId;
                    tStr[3] = tGSOrderAuthorizeVO.manufactureName;
                    tStr[4] = String.valueOf(tGSOrderAuthorizeVO.orderCount);
                    tStr[5] = tGSOrderAuthorizeVO.deliverDate;
                    tStr[6] = tGSOrderAuthorizeVO.deliverTime;
                    // tStr[7] = tGSOrderAuthorizeVO.orderDeptId;
                    // tStr[8] = tGSOrderAuthorizeVO.deliverAddr;
                    // tStr[9] = tGSOrderAuthorizeVO.contactName;
                    // tStr[10] = tGSOrderAuthorizeVO.contactPhone;
                    // tStr[11] = tGSOrderAuthorizeVO.deliverMode;
                    // tStr[12] = tGSOrderAuthorizeVO.balanceMode;
                    // tStr[13] = tGSOrderAuthorizeVO.orderid;
                    // tStr[14] =
                    // tGSOrganizationDAO.getOrg(tGSOrderAuthorizeVO.orderDeptId).getGs_org_name();
                    // 根据集中编码查询特约供应商/非特约供应商
                    ArrayList tempList = tGSProviderDAO.queryManufactureProvider(tConn, tGSOrderAuthorizeVO.concentricityId);
                    ArrayList provList = new ArrayList();
                    for (int j = 0; j < tempList.size(); j++) {
                        GSProviderBean tGSProviderBean = (GSProviderBean) tempList.get(j);
                        String[] pStr = new String[] { tGSProviderBean.getGs_provider_id(), tGSProviderBean.getGs_provider_name() };
                        provList.add(pStr);
                    }

                    tGSOrderVO.tList.add(tStr);
                    tGSOrderVO.pList.add(provList);
                }
            }
        } catch (GSException ge) {
            throw ge;
        } catch (Exception e) {
            GSLogWriter.debug(this, e.toString());
            throw new GSException(GSException.E10041, GSException.E10041_MSG);
        } finally {
            GSOrderDAO.close(tConn);
        }
        return tGSOrderVO;

    }

    /**
     * 根据订单号得到所需的订单细节(for订单审核)
     * 
     * @param aGSOrderVO
     * @return
     * @throws GSException
     */
    public GSOrderVO getOrderAndManufacture(String orderId) throws GSException {
        GSOrderDAO tGSOrderDAO = new GSOrderDAO();
        GSOrderVO tGSOrderVO = new GSOrderVO();
        Connection tConn = null;
        try {
            tConn = tGSOrderDAO.getConnetion();
            // 根据订单编号查询订单对象和订单明细对象
            GSOrderBean orderBean = tGSOrderDAO.getOrderByTempID(orderId);
            tGSOrderVO.orderid = orderBean.getGs_order_tempid();
            tGSOrderVO.category = GSBaseManager.getOrderCategoryName(orderBean.getGs_order_category());
            tGSOrderVO.orderStatus = GSBaseManager.getOrderStatusName(orderBean.getGs_order_status());
            tGSOrderVO.tList = new ArrayList();

            ArrayList tOrderDetailList = tGSOrderDAO.queryOrderAndDetail(tConn, orderId);
            if (tOrderDetailList.size() > 0) {

                for (int i = 0; i < tOrderDetailList.size(); i++) {
                    GSOrderAuditVO tGSOrderAuditVO = (GSOrderAuditVO) tOrderDetailList.get(i);

                    String[] tStr = new String[11];
                    tStr[0] = tGSOrderAuditVO.orderid;
                    tStr[1] = "";
                    tStr[2] = "";
                    tStr[3] = tGSOrderAuditVO.detailId;
                    tStr[4] = tGSOrderAuditVO.manufactureId;
                    tStr[5] = tGSOrderAuditVO.manufactureName;
                    tStr[6] = String.valueOf(tGSOrderAuditVO.orderCount);
                    tStr[7] = GSBaseManager.getOrderDeptName(tGSOrderAuditVO.orderDeptId);
                    tStr[8] = tGSOrderAuditVO.concentricityId;
                    tStr[9] = GSBaseManager.getDeliverModeName(tGSOrderAuditVO.deliverMode);
                    tStr[10] = GSBaseManager.getBalanceModeName(tGSOrderAuditVO.balanceMode);

                    tGSOrderVO.tList.add(tStr);

                }
            }
        } catch (GSException ge) {
            throw ge;
        } catch (Exception e) {
            GSLogWriter.debug(this, e.toString());
            throw new GSException(GSException.E10041, GSException.E10041_MSG);
        } finally {
            GSOrderDAO.close(tConn);
        }
        return tGSOrderVO;
    }

    /**
     * 审核不通过，不必记录修改内容
     * 
     * @param map
     * @param aBean
     * @throws GSException
     */
    public void unAuthorizeOrder(String[] indexs, LoginContext aBean, String msg) throws GSException {

        GSBusOrderDetailDAO odd = new GSBusOrderDetailDAO();
        Connection conn = null;

        // edit by Jackey start
        String sqlOrderDetail = new StringBuffer("update GS_ORDER_DETAIL set ").append(" GS_ORDER_DETAIL_STATUS = '8', GS_AUTHORIZE_ADVICES = ?, ").append(
                " GS_AUTHORIZER_ID = ?, GS_AUTHORIZE_DATE = to_char(sysdate,'yyyy-mm-dd hh24:mi:ss'), ").append(
                " GS_LASTMODIFER_ID = ?, GS_LASTMODIFY_CONTENTS = '订单核准', GS_LASTMODIFY_DATE = to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') ").append(
                " where GS_ORDER_DETAIL_ID = ?").toString();

        // edit by Jackey end

        try {
            conn = odd.getConnetion();
            conn.setAutoCommit(false);
            PreparedStatement pstmt2 = conn.prepareStatement(sqlOrderDetail);
            for (int i = 0; i < indexs.length; i++) {
                String detailId = indexs[i];

                pstmt2.setString(1, msg);
                pstmt2.setString(2, aBean.getLoginUserId());
                pstmt2.setString(3, aBean.getLoginUserId());
                pstmt2.setString(4, detailId);
                pstmt2.addBatch();
            }
            pstmt2.executeBatch();
            conn.commit();

        } catch (Exception e) {
            try {
                conn.rollback();
            } catch (SQLException sqle) {

            }
            throw new GSException(GSException.E20056, GSException.E20056_MSG);
        } finally {
            try {
                conn.setAutoCommit(true);
            } catch (SQLException sqle) {

            }
            GSBusOrderDetailDAO.close(conn);
        }

    }

    /**
     * 审核订单，需要同时记录修改的订单明细内容
     * 
     * @param ary
     * @param aBean
     * @throws GSException
     */
    public void authorizeOrder(LoginContext aBean, ArrayList ary) throws GSException {
        GSBusOrderDAO dao = new GSBusOrderDAO();

        Connection conn = null;

        // String sqlOrder = "update GS_ORDER set GS_AUTHORIZER_ID =
        // ?,GS_AUTHORIZE_DATE = to_char(sysdate,'yyyy-mm-dd
        // hh24:mi:ss'),gs_order_sum = ? where GS_ORDER_TEMPID =?";
        String sqlOrderDetail = new StringBuffer("update GS_ORDER_DETAIL set GS_MANUFACTURE_ID = ?,").append(
                "GS_ORDER_COUNT = ?, GS_PROVIDER_ID = ?, GS_GOODS_UNITPRICE = ?, GS_ORDER_DETAIL_STATUS = '7', ").append(
                "GS_AUTHORIZER_ID = ?, GS_AUTHORIZE_DATE = to_char(sysdate,'yyyy-mm-dd hh24:mi:ss'), ").append(
                "GS_LASTMODIFER_ID = ?, GS_LASTMODIFY_CONTENTS = '订单核准', GS_LASTMODIFY_DATE = to_char(sysdate,'yyyy-mm-dd hh24:mi:ss'), ").append(
                "GS_DELIVER_GOODS_DATE = ?, GS_DELIVER_GOODS_TIME = ?,gs_balance_mode=? ").append(" where GS_ORDER_DETAIL_ID = ?").toString();
        try {
            conn = dao.getConnetion();
            conn.setAutoCommit(false);

            // PreparedStatement pstmt1 = conn.prepareStatement(sqlOrder);
            PreparedStatement pstmt2 = conn.prepareStatement(sqlOrderDetail);

            for (int i = 0; i < ary.size(); i++) {
                GSOrderAuthorizeSaveVO vo = (GSOrderAuthorizeSaveVO) ary.get(i);

                // 计算订单明细的总价
                // BigDecimal new_totalPrice = new
                // BigDecimal(vo.orderCount).multiply(new
                // BigDecimal(vo.unitPrice));
                // BigDecimal old_totalPrice = new
                // BigDecimal(vo.oldOrderCount).multiply(new
                // BigDecimal(vo.oldUnitPrice));
                pstmt2.setString(1, vo.manufactureId);
                pstmt2.setString(2, vo.orderCount);
                pstmt2.setString(3, vo.providerId);
                pstmt2.setString(4, vo.unitPrice);
                pstmt2.setString(5, aBean.getLoginUserId());
                pstmt2.setString(6, aBean.getLoginUserId());

                pstmt2.setString(7, vo.deliverDate);
                pstmt2.setString(8, vo.deliverTime);
                pstmt2.setString(9, vo.mode);
                pstmt2.setString(10, vo.detailId);
                pstmt2.addBatch();

                // pstmt1.setString(1,aBean.getGs_oper_id());
                // 更新订单总价，对每一个明细都更新一次
                // pstmt1.setDouble(2,new_totalPrice.subtract(old_totalPrice).doubleValue());
                // pstmt1.setString(3,vo.orderId);
                // pstmt1.addBatch();

            }
            pstmt2.executeBatch();
            // pstmt1.executeBatch();
            conn.commit();

        } catch (Exception e) {
            try {
                conn.rollback();
            } catch (SQLException sqle) {

            }
            throw new GSException(GSException.E20056, GSException.E20056_MSG);
        } finally {
            try {
                conn.setAutoCommit(true);
            } catch (SQLException sqle) {

            }
            GSBusOrderDAO.close(conn);
        }

    }
    /**
     * 直接将状态为已提交订单提交到交易平台
     * 
     * @param aBean
     *            操作员对象
     * @param ary
     * @return
     * @throws GSException
     */
    public String orderSubmitToApep(LoginContext aBean, ArrayList ary,String applyCode) throws GSException {
        GSBusOrderDAO tOrderDAO = new GSBusOrderDAO();
        Connection tConn = null;
        boolean tFlag = false;
        String msg = "";
        String tRs = "";
        int err = 0;
        int ok = 0;
        try {
            tConn = tOrderDAO.getConnetion();
            tConn.setAutoCommit(false);
            GSOrderDetailDAO tOrderDetailDAO = new GSOrderDetailDAO();
            // 查询出订单明细编号对应订单明细为提交到交易平台做准备
            for (int i = 0; i < ary.size(); i++) {
                GSOrderAuthorizeSaveVO tVO = (GSOrderAuthorizeSaveVO) ary.get(i);
                GSOrderAnaDetailAndCategoryBean tOrderManufVO = tOrderDetailDAO.getOrderDetailByDetailId(tVO.detailId);
                tOrderManufVO.setGs_order_count(Double.parseDouble(tVO.orderCount));
                tOrderManufVO.setApep_code(tVO.manufactureId);
                tOrderManufVO.setGs_goods_unitprice(Double.parseDouble(tVO.unitPrice));
                tOrderManufVO.setGs_deliver_goods_date(tVO.deliverDate);
                tOrderManufVO.setGs_deliver_goods_time(tVO.deliverTime);
                String dmode=GSBaseManager.getDictioanryName(tOrderManufVO.getGs_deliver_mode());
                tOrderManufVO.setGs_deliver_mode(dmode);
                String bmode=GSBaseManager.getDictioanryName(tOrderManufVO.getGs_balance_mode_order());
                tOrderManufVO.setGs_balance_mode_order(bmode);
                // 创建订单明细bean对象，设定待修改数据
                GSOrderAnaDetailAndCategoryBean tOrderDetailBean = new GSOrderAnaDetailAndCategoryBean();
                tOrderDetailBean.setGs_order_detail_id(tVO.detailId);
                // 保存修改的订单内容
                tOrderDetailBean.setGs_order_count(Double.parseDouble(tVO.orderCount));
                tOrderDetailBean.setGs_provider_id(tVO.providerId);
                tOrderDetailBean.setGs_goods_unitprice(Double.parseDouble(tVO.unitPrice));
                tOrderDetailBean.setGs_manufacture_id(tVO.manufactureId);
                // 订货中
                tOrderDetailBean.setGs_order_detail_status(GSBaseConstants.ORDER_ORDERING);
                tOrderDetailBean.setGs_lastmodifer_id(aBean.getLoginUserId());
                String tCurDT = DateUtil.getCurrentTime("DT", "AD");
                tCurDT = DateUtil.formateDateTime(tCurDT);
                tOrderDetailBean.setGs_lastmodify_date(tCurDT);
                tOrderDetailBean.setGs_lastmodify_contents("订单直接审核通过后提交");
                tOrderDetailBean.setGs_submiter_id2(aBean.getLoginUserId());
                tOrderDetailBean.setGs_submit_date2(tCurDT);

                tOrderDetailBean.setGs_deliver_goods_date(tVO.deliverDate);
                tOrderDetailBean.setGs_deliver_goods_time(tVO.deliverTime);
                tOrderDetailBean.setGs_authorizer_id(aBean.getLoginUserId());

                // 修改订单明细状态为订货中
                tFlag = tOrderDetailDAO.updateDetailAsOrdering(tOrderDetailBean, tConn);
                if (tFlag) {
                    // 执行订单提交
                    tRs = GSCommunicationApepProcessor.submitOrderDetailNewToApep(tOrderManufVO, aBean,applyCode);
                    String[] result=GSCommunicationApepProcessor.parseReturnXml(tRs);
                    if (result[0].equals(GSBaseConstants.APEP_RETURN_SIGN_SUCCESS)) {
                        tConn.commit();
                        ok++;
                        GSLogWriter.info(this, "提交成功");
                    } else {
                        tConn.rollback();
                        err++;
                        GSLogWriter.error(this, "提交失败");
                    }
                    // 判断返回结果
                    tOrderDetailDAO.updateORDERRETURNSIGN(tOrderManufVO.getGs_order_detail_id(),result[0],result[1]);
                } else {
                    GSLogWriter.debug(this, "修改订单明细状态为提交失败");
                    tConn.rollback();
                    break;
                }
            }
            if (err == 0) {
                msg = "有" + ok + "笔订单提交成功";
            } else if (err > 0) {
                msg = "有" + ok + "笔订单提交成功,有" + err + "笔订单APEP无法提供网上处理,您可以在手动订单处理功能中查看并进行处理。";
            }
        } catch (GSException ge) {
            try {
                tConn.rollback();
            } catch (SQLException se) {
                se.printStackTrace();
            }
            throw ge;
        } catch (Exception e) {
            try {
                tConn.rollback();
            } catch (SQLException sqle) {
                sqle.printStackTrace();
            }
            GSLogWriter.error(this, e.toString());
            throw new GSException(GSException.E20056, GSException.E20056_MSG);
        } finally {
            try {
                tConn.setAutoCommit(true);
            } catch (SQLException sqle) {
                GSLogWriter.error(this, GSException.E19994_MSG);
            }
            GSBusOrderDAO.close(tConn);
        }
        return msg;

    }
    /**
     * 直接将状态为复审通过订单提交到交易平台
     * 
     * @param aBean
     *            操作员对象
     * @param ary 订单编号
     * @return
     * @throws GSException
     */
    public String orderSubmitNewToApep(LoginContext aBean, ArrayList ary,String[] applyCode) throws GSException {
        GSOrderDetailDAO detailDao=new GSOrderDetailDAO();
        GSManufactureDAO manufactureDao=new GSManufactureDAO();
        Connection tConn = null;
        boolean tFlag = false;
        String msg = "";
        String tRs = "";
        int err = 0;
        int ok = 0;
        try {
            tConn = detailDao.getConnetion();
            tConn.setAutoCommit(false);
            // 查询出订单明细编号对应订单明细为提交到交易平台做准备
            for (int i = 0; i < ary.size(); i++) {
                GSOrderAuthorizeSaveVO tVO = (GSOrderAuthorizeSaveVO) ary.get(i);
                GSOrderAnaDetailAndCategoryBean detailBean = detailDao.getOrderDetailByDetailId(tVO.detailId);
                // 修改订单明细状态为订货中
                if(detailBean==null){
                	 throw new GSException("产品编码为:"+tVO.productCode+",出现异常！");
                }
                detailBean.setGs_order_detail_status(GSBaseConstants.ORDER_ORDERING);
                detailBean.setGs_lastmodifer_id(aBean.getLoginUserId());
                String tCurDT = DateUtil.getCurrentTime("DT", "AD");
                tCurDT = DateUtil.formateDateTime(tCurDT);
                detailBean.setGs_lastmodify_date(tCurDT);
                detailBean.setGs_lastmodify_contents("订单直接审核通过后提交");
                detailBean.setGs_submiter_id2(aBean.getLoginUserId());
                detailBean.setGs_submit_date2(tCurDT);
                detailBean.setGs_authorizer_id(aBean.getLoginUserId());
                tFlag = detailDao.updateDetailAsOrdering(detailBean, tConn);
              //更新产品isupdate属性
                tFlag = manufactureDao.modify(tConn, detailBean.getId_product(), GSBaseConstants.NO_UPDATE);
                if (tFlag) {
                    // 执行订单提交
                    String t="";
                    if(applyCode!=null){
                        t=applyCode[i];
                    }
                    tRs = GSCommunicationApepProcessor.submitOrderDetailNewToApep(detailBean, aBean,t);
                    String[] result=GSCommunicationApepProcessor.parseReturnXml(tRs);
                    if (result[0].equals(GSBaseConstants.APEP_RETURN_SIGN_SUCCESS)) {
                        tConn.commit();
                        ok++;
                        GSLogWriter.info(this, "提交成功");
                    } else {
                        tConn.rollback();
                        err++;
                        GSLogWriter.error(this, "提交失败");
                    }
                    // 判断返回结果
                    detailDao.updateORDERRETURNSIGN(detailBean.getGs_order_detail_id(),result[0],result[1]);
                } else {
                    GSLogWriter.debug(this, "修改订单明细状态为提交失败");
                    tConn.rollback();
                    break;
                }
            }
            if (err == 0) {
                msg = "有" + ok + "笔订单提交成功";
            } else if (err > 0) {
                msg = "有" + ok + "笔订单提交成功,有" + err + "笔订单APEP无法提供网上处理,您可以在手动订单处理功能中查看原因并进行打印处理。";
            }
        } catch (GSException ge) {
            try {
                tConn.rollback();
            } catch (SQLException se) {
                se.printStackTrace();
            }
            throw ge;
        } catch (Exception e) {
            try {
                tConn.rollback();
            } catch (SQLException sqle) {
                sqle.printStackTrace();
            }
            GSLogWriter.error(this, e.toString());
            throw new GSException("订单提交失败！");
        } finally {
            try {
                tConn.setAutoCommit(true);
            } catch (SQLException sqle) {
                GSLogWriter.error(this, GSException.E19994_MSG);
            }
            GSBusOrderDAO.close(tConn);
        }
        return msg;

    }
    /**
     * 在运营公司端订单提交页面将状态为已审核订单提交到交易平台
     * 
     * @param aBean
     *            操作员对象
     * @param ary
     * @return
     * @throws GSException
     */
    public String orderSubmitInSubmitToApep(LoginContext aBean, ArrayList ary) throws GSException {
        GSBusOrderDAO tOrderDAO = new GSBusOrderDAO();
        Connection tConn = null;
        boolean tFlag = false;
        String msg = "";
        String tRs = "";
        int err = 0;
        int ok = 0;
        try {
            tConn = tOrderDAO.getConnetion();
            tConn.setAutoCommit(false);
            GSOrderDetailDAO tOrderDetailDAO = new GSOrderDetailDAO();
            // 查询出订单明细编号对应订单明细为提交到交易平台做准备
            for (int i = 0; i < ary.size(); i++) {
                GSOrderAuthorizeSaveVO tVO = (GSOrderAuthorizeSaveVO) ary.get(i);
                GSOrderManufactureVO tOrderManufVO = new GSOrderManufactureVO();
                tOrderManufVO.orderDetailId = tVO.detailId;
                tOrderManufVO.ordercount = tVO.orderCount;
                tOrderManufVO.manufactureid = tVO.manufactureId;
                tOrderManufVO.manufactureUnitPrice = Double.parseDouble(tVO.unitPrice);
                tOrderManufVO.orderId = tVO.orderId;
                // 创建订单明细bean对象，设定待修改数据
                GSOrderDetailBean tOrderDetailBean = new GSOrderDetailBean();
                tOrderDetailBean.setGs_order_detail_id(tVO.detailId);
                // 保存修改的订单内容
                tOrderDetailBean.setGs_order_count(Double.parseDouble(tVO.orderCount));
                tOrderDetailBean.setGs_provider_id(tVO.providerId);
                tOrderDetailBean.setGs_goods_unitprice(Double.parseDouble(tVO.unitPrice));
                tOrderDetailBean.setGs_manufacture_id(tVO.manufactureId);
                // 修改订单状态为订货中
                tOrderDetailBean.setGs_order_detail_status(GSBaseConstants.ORDER_ORDERING);
                tOrderDetailBean.setGs_lastmodifer_id(aBean.getLoginUserId());
                String tCurDT = DateUtil.getCurrentTime("DT", "AD");
                tCurDT = DateUtil.formateDateTime(tCurDT);
                tOrderDetailBean.setGs_lastmodify_date(tCurDT);
                tOrderDetailBean.setGs_lastmodify_contents("订单直接审核通过后提交");
                tOrderDetailBean.setGs_submiter_id2(aBean.getLoginUserId());
                tOrderDetailBean.setGs_submit_date2(tCurDT);
                // 修改订单明细状态为订货中
//                tFlag = tOrderDetailDAO.updateDetailAsOrdering(tOrderDetailBean, tConn);
//                if (tFlag) {
//                    // 执行订单提交
//                    tRs = submitOrderDetailToApep(tOrderManufVO, aBean);
//                    // 判断返回结果
//                    if (tRs.equals("1")) {
//                        tConn.commit();
//                        ok++;
//                        GSLogWriter.info(this, "提交成功");
//                        tOrderDetailDAO.updateORDERRETURNSIGN(tOrderManufVO.orderDetailId, GSBaseConstants.APEP_RETURN_SIGN_OK);
//                    } else {
//                        tConn.rollback();
//                        err++;
//                        GSLogWriter.error(this, "提交失败");
//                        tOrderDetailDAO.updateORDERRETURNSIGN(tOrderManufVO.orderDetailId, GSBaseConstants.APEP_RETURN_SIGN_FAIL);
//                    }
//                } else {
//                    GSLogWriter.debug(this, "修改订单明细状态为提交失败");
//                    tConn.rollback();
//                    break;
//                }
            }
            if (err == 0) {
                msg = "有" + ok + "笔订单提交成功";
            } else if (err > 0) {
                msg = "有" + ok + "笔订单提交成功,有" + err + "笔订单APEP无法提供网上处理,您可以在手动订单处理功能中进行打印处理。";
            }
        } catch (GSException ge) {
            try {
                tConn.rollback();
            } catch (SQLException se) {
                se.printStackTrace();
            }
            throw ge;
        } catch (Exception e) {
            try {
                tConn.rollback();
            } catch (SQLException sqle) {
                sqle.printStackTrace();
            }
            GSLogWriter.error(this, e.toString());
            throw new GSException(GSException.E20056, GSException.E20056_MSG);
        } finally {
            try {
                tConn.setAutoCommit(true);
            } catch (SQLException sqle) {
                GSLogWriter.error(this, GSException.E19994_MSG);
            }
            GSBusOrderDAO.close(tConn);
        }
        return msg;

    }

    /**
     * 巴士物资提交订单到交易平台_逐一提交
     * 
     * @param aList
     *            待提交订单明细
     * @param aOperBean
     *            操作员对象
     * @return
     * @throws GSException
     */
    public String submitOrderDetailToApep(GSOrderManufactureVO tOrderManufVO, LoginContext aOperBean) throws GSException {
        String tRs = "";
        try {
            // 读取采购网给巴士物资的编码
            String tPurCode = GSSystemConfigurator.getParam("gs.purcode");
            String tWorkDT = DateUtil.formateDateTime(DateUtil.getCurrentTime("DT", "AD"));
            if (tOrderManufVO != null) {
                ParameterFactory pf = new ParameterFactory();
                GSOrderDAO orddao = new GSOrderDAO();
                String purName = "";
                purName = orddao.getWorkCorp(tOrderManufVO.orderId);
                // 组装要发送到采购网的内容
                pf.clear();
                pf.addParam("Action", "CreateOrder");
                pf.addParam("Count", "1");
                pf.addParam("Total", "1"); // tOrderManufVO.ordercount
                pf.addParam("CusOrderItemCode_0", tOrderManufVO.orderDetailId); // +i
                pf.addParam("ProductID_0", tOrderManufVO.manufactureid);
                pf.addParam("CusItemCode_0", tOrderManufVO.concentricityId);
                pf.addParam("Price_0", String.valueOf(tOrderManufVO.manufactureUnitPrice));
                pf.addParam("Qty_0", tOrderManufVO.ordercount);
                pf.addParam("SendMode_0", tOrderManufVO.delivermode);
                pf.addParam("PayMode_0", tOrderManufVO.balancemode);
                pf.addParam("SendRequire_0", tOrderManufVO.deliverdate == null ? "" : tOrderManufVO.deliverdate + " "
                        + (tOrderManufVO.delivertime == null ? "" : GSBaseManager.getDeliverGoodsTime(tOrderManufVO.delivertime)));
                pf.addParam("Address_0", tOrderManufVO.deliveraddr);
                pf.addParam("LinkPerson_0", tOrderManufVO.linkman == null ? "" : tOrderManufVO.linkman);
                pf.addParam("LinkPhone_0", tOrderManufVO.linktel == null ? "" : tOrderManufVO.linktel);
                pf.addParam("CusCode_0", tPurCode);
                pf.addParam("PurName_0", purName);
                pf.addParam("Remark_0", tOrderManufVO.orderDetailNote == null ? "" : tOrderManufVO.orderDetailNote);
                pf.addParam("CreateTime_0", tWorkDT);
                pf.addParam("PurName_0", purName);
                pf.addParam("SubmitPerson_0", aOperBean.getLoginUserName());
                GSLogWriter.debug(this, "传送内容" + pf.getStrStream());
                // http方式
                // 连接服务端
                String tHttp = GSSystemConfigurator.getParam("gs.HttpServletUrl");
                GSClientSocket tClientHttp = new GSClientSocket(tHttp);
                // 发送订单信息到采购网
                tRs = tClientHttp.sendContents(pf.getStrStream());
            } else {
                GSLogWriter.error(this, "无可提交订单明细");
            }
        } catch (GSException ge) {
            throw ge;
        } catch (Exception e) {
            GSLogWriter.error(this, e.toString());
            throw new GSException(GSException.E00001, GSException.E00001_MSG);
        }
        return tRs;
    }

    /**
     * 巴士物资提交订单到交易平台_old
     * 
     * @param aList
     *            待提交订单明细
     * @param aOperBean
     *            操作员对象
     * @return
     * @throws GSException
     */
    public String submitOrderDetailToApepOld(ArrayList aList, GSOperatorBean aOperBean) throws GSException {
        String tRs = "";
        try {
            // 读取采购网给巴士物资的编码
            String tPurCode = GSSystemConfigurator.getParam("gs.purcode");
            String tWorkDT = DateUtil.formateDateTime(DateUtil.getCurrentTime("DT", "AD"));
            if (aList.size() > 0) {
                BigDecimal tTotal = new BigDecimal("0");
                for (int i = 0; i < aList.size(); i++) {
                    GSOrderManufactureVO tVO = (GSOrderManufactureVO) aList.get(i);
                    String count = tVO.ordercount;
                    tTotal = tTotal.add(new BigDecimal(count));
                }
                GSOrderDAO orddao = new GSOrderDAO();
                String purName = "";
                // 组装要发送到采购网的内容
                ParameterFactory pf = new ParameterFactory();
                pf.addParam("Action", "CreateOrder");
                pf.addParam("Count", String.valueOf(aList.size()));
                pf.addParam("Total", tTotal.toString());
                for (int i = 0; i < aList.size(); i++) {
                    GSOrderManufactureVO tOrderManufVO = (GSOrderManufactureVO) aList.get(i);
                    purName = orddao.getWorkCorp(tOrderManufVO.orderId);
                    pf.addParam("CusOrderItemCode_" + i, tOrderManufVO.orderDetailId);
                    pf.addParam("ProductID_" + i, tOrderManufVO.manufactureid);
                    pf.addParam("CusItemCode_" + i, tOrderManufVO.concentricityId);
                    pf.addParam("Price_" + i, String.valueOf(tOrderManufVO.manufactureUnitPrice));
                    pf.addParam("Qty_" + i, tOrderManufVO.ordercount);
                    pf.addParam("SendMode_" + i, tOrderManufVO.delivermode);
                    pf.addParam("PayMode_" + i, tOrderManufVO.balancemode);
                    pf.addParam("SendRequire_" + i, tOrderManufVO.deliverdate == null ? "" : tOrderManufVO.deliverdate + " "
                            + (tOrderManufVO.delivertime == null ? "" : GSBaseManager.getDeliverGoodsTime(tOrderManufVO.delivertime)));
                    pf.addParam("Address_" + i, tOrderManufVO.deliveraddr);
                    pf.addParam("LinkPerson_" + i, tOrderManufVO.linkman == null ? "" : tOrderManufVO.linkman);
                    pf.addParam("LinkPhone_" + i, tOrderManufVO.linktel == null ? "" : tOrderManufVO.linktel);
                    pf.addParam("CusCode_" + i, tPurCode);
                    pf.addParam("PurName_" + i, purName);
                    pf.addParam("Remark_" + i, tOrderManufVO.orderDetailNote == null ? "" : tOrderManufVO.orderDetailNote);
                    pf.addParam("CreateTime_" + i, tWorkDT);
                    pf.addParam("PurName_" + i, purName);
                    pf.addParam("SubmitPerson_" + i, aOperBean.getGs_oper_name());
                }
                // 最后添加结束符 "&"

                GSLogWriter.debug(this, "传送内容" + pf.getStrStream());
                // 取得配置文件中服务端IP和端口参数
                String tIP = GSSystemConfigurator.getParam("gs.ip");
                String tPort = GSSystemConfigurator.getParam("gs.port");
                // 连接服务端
                GSClientSocket tClientSocket = new GSClientSocket(tIP, Integer.parseInt(tPort));

                // 发送订单信息到采购网
                tRs = tClientSocket.sendContents(pf.getStrStream());
                // 判断返回结果
                if (tRs.equals("1")) {
                    // tConn.commit();
                    GSLogWriter.info(this, "提交返回成功");
                } else {
                    // tConn.rollback();
                    GSLogWriter.error(this, "提交返回失败");
                }
            } else {
                GSLogWriter.error(this, "无可提交订单明细");
            }
        } catch (GSException ge) {
            throw ge;
        } catch (Exception e) {
            GSLogWriter.error(this, e.toString());
            throw new GSException(GSException.E00001, GSException.E00001_MSG);
        }
        return tRs;
    }

    /**
     * 查询一个订单的所有明细，用于订单录入
     * 
     * @param orderId
     * @return
     * @throws GSException
     */
    public ArrayList getOrderDetail(String orderId) throws GSException {
        ArrayList tList = new ArrayList();
        try {
            GSBusOrderDetailDAO tGSBusOrderDetailDAO = new GSBusOrderDetailDAO();
            // 查询订单明细
            ArrayList tRs = tGSBusOrderDetailDAO.queryOrderDetail_(orderId);
            if (tRs.size() > 0) {
                for (int i = 0; i < tRs.size(); i++) {
                    String[] tStr = new String[17];
                    GSBusOrderManufactureVO_ tGSBusOrderManufactureVO = (GSBusOrderManufactureVO_) tRs.get(i);
                    // 取出订单包含的产品信息VO对象组成String数组
                    tStr[0] = tGSBusOrderManufactureVO.orderTempId;
                    tStr[1] = tGSBusOrderManufactureVO.orderDetailId;
                    tStr[2] = tGSBusOrderManufactureVO.manufactureId;
                    tStr[3] = tGSBusOrderManufactureVO.manufactureName;
                    tStr[4] = tGSBusOrderManufactureVO.contentricityId;
                    tStr[5] = tGSBusOrderManufactureVO.orderCount;
                    tStr[6] = tGSBusOrderManufactureVO.deliverGoodsDate;
                    tStr[7] = GSBaseManager.getDeliverGoodsTime(tGSBusOrderManufactureVO.deliverGoodsTime);
                    tStr[8] = tGSBusOrderManufactureVO.manufactureSpec;
                    tStr[9] = tGSBusOrderManufactureVO.manufactureType;
                    tStr[10] = tGSBusOrderManufactureVO.manufactrueBrand;
                    tStr[11] = tGSBusOrderManufactureVO.quantUnit;
                    tStr[12] = tGSBusOrderManufactureVO.unitPrice;
                    tStr[13] = tGSBusOrderManufactureVO.period;
                    tStr[14] = tGSBusOrderManufactureVO.balanceCategory;
                    tStr[15] = tGSBusOrderManufactureVO.mode;
                    tStr[16] = DefineDic.getBalanceMode(tGSBusOrderManufactureVO.mode);
                    // tStr[8] = tGSOrderManufactureVO.orgName;
                    // tStr[9] = tGSOrderManufactureVO.deliverGoodsAddr;
                    // tStr[10] = tGSOrderManufactureVO.getContactName();
                    // tStr[11] = tGSOrderManufactureVO.getContactPhone();
                    // tStr[12] = tGSOrderManufactureVO.deliverMode;
                    // tStr[13] = tGSOrderManufactureVO.balanceMode;
                    tList.add(tStr);
                }
            }
        } catch (GSException ge) {
            throw ge;
        } catch (Exception e) {
            GSLogWriter.error(this, e.toString());
            throw new GSException(GSException.E10042, GSException.E10042_MSG);
        }
        return tList;

    }

    /**
     * 从订单编号获得订单Bean
     * 
     * @param orderCode
     *            订单编号
     * @return
     * @throws GSException
     */
    public GSOrderBean selectOrderByCode(String orderCode) throws GSException {

        GSOrderBean tGSOrderBean = new GSOrderBean();

        GSBusOrderDAO ordd = new GSBusOrderDAO();
        tGSOrderBean = ordd.selectOrderByCode(orderCode);

        return tGSOrderBean;
    }

    /**
     * 集中采购提交订单签收性息到APEP交易平台
     * 
     * @param aList
     *            待提交订单明细
     * @param aOperBean
     *            操作员对象
     * @return
     * @throws GSException
     */
    public String submitOrderReciveInfoToApep(GSOrderReceiveQueryVO tGSOrderReceiveQueryVO, GSOperatorBean aOperBean) throws GSException {
        String tRs = "";
        try {
            // 读取采购网给巴士物资的编码
            String tPurCode = GSSystemConfigurator.getParam("gs.purcode");
            if (tGSOrderReceiveQueryVO != null) {
                String tWorkDT = DateUtil.formateDateTime(DateUtil.getCurrentTime("DT", "AD"));
                ParameterFactory pf = new ParameterFactory();
                // 组装要发送到采购网的内容
                pf.clear();
                // 明确拒绝产品不提交
                if (!GSBaseConstants.APEP_RETURN_SIGN_SUCCESS.equals(tGSOrderReceiveQueryVO.sign)||"-1".equals(tGSOrderReceiveQueryVO.sign)) {
                    tRs = "1";
                    return tRs;
                }
                pf.addParam("Action", "ReceiveOrder");
                pf.addParam("Count", "1");

                // 采购商代码
                pf.addParam("CusCode_0", tPurCode);

                // 集中采购的订单明细编号
                pf.addParam("CusOrderItemCode_0", tGSOrderReceiveQueryVO.orderDetailId);

                // 签收时间
                pf.addParam("ReceiveTime_0", tGSOrderReceiveQueryVO.signin_date);

                // 签收数量
                pf.addParam("ReceiveQty_0", "" + tGSOrderReceiveQueryVO.signinCount);

                // 签收人
                pf.addParam("ReceivePerson_0", tGSOrderReceiveQueryVO.signin_person);

                // 签收创建时间
                pf.addParam("ReceiveCreateTime_0", tWorkDT);

                // 签收备注
                pf.addParam("Remark_0", tGSOrderReceiveQueryVO.signin_explain);

                GSLogWriter.debug(this, "传送内容" + pf.getStrStream());

                // http方式
                // 连接服务端
                String tHttp = GSSystemConfigurator.getParam("gs.HttpServletUrl");
                GSClientSocket tClientHttp = new GSClientSocket(tHttp);
                // 发送订单信息到采购网
                tRs = tClientHttp.sendContents(pf.getStrStream());
            } else {
                GSLogWriter.error(this, "无可提交订单明细");
            }
        } catch (GSException ge) {
            throw ge;
        } catch (Exception e) {
            GSLogWriter.error(this, e.toString());
            throw new GSException(GSException.E00001, GSException.E00001_MSG);
        }
        return tRs;
    }

}
